import {login, logout} from '../../api/login.ts'
import type {LoginData} from '../../api/login.ts'
import {getToken, removeToken, setToken,} from '../../utils/auth'
import {defineStore} from "pinia";
import router from "../../router";


const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [] as any,
      permissions: [] as any,
    }),
    actions: {
      // 登录
      login(userInfo:LoginData) {
        const userName = userInfo.userName!.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise<void>((resolve, reject) => {
          login({userName, password, code, uuid}).then(res => {
            if(res!.code==200){
              if(res!.token){
                setToken(res.token)
                this.token = res.token
                router.push({path: "/redirect",}).then();
               }

            }



            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      // getInfo() {
      //   return new Promise((resolve, reject) => {
      //     getInfo().then(res => {
      //       const user = res.user
      //       const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
      //
      //       if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
      //         this.roles = res.roles
      //         this.permissions = res.permissions
      //       } else {
      //         this.roles = ['ROLE_DEFAULT']
      //       }
      //       this.id = user.userId
      //       this.name = user.userName
      //       this.avatar = avatar
      //       resolve(res)
      //     }).catch(error => {
      //       reject(error)
      //     })
      //   })
      // },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            // resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
